package com.mingmen.canting.chushizhang;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.mingmen.canting.R;
import com.mingmen.canting.base.BaseBean;
import com.mingmen.canting.fragment.BaseFragment;
import com.mingmen.canting.http.callback.StringCallback;
import com.mingmen.canting.httpconfig.HttpResponse;
import com.mingmen.canting.model.ChushiShenHeModel;
import com.mingmen.canting.model.EventBean;
import com.mingmen.canting.model.ShopListModel;
import com.mingmen.canting.util.GsonUtil;
import com.mingmen.canting.util.MyStringUtils;
import com.mingmen.canting.util.SharePreferenceUtil;
import com.mingmen.canting.zhenban.ZhenBanDingDanActivity;
import com.mingmen.canting.zhenbanlibrary.CheckListener;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import de.greenrobot.event.EventBus;
import okhttp3.Call;
import okhttp3.Response;

@SuppressLint("ValidFragment")
public class ChaKancaigourfagment extends BaseFragment implements CheckListener {

    String mTitle;

    Unbinder unbinder;
    @BindView(R.id.card_title_tv)
    TextView cardTitleTv;
    @BindView(R.id.rv_sort)
    RecyclerView rvSort;
    @BindView(R.id.lin_fragment)
    FrameLayout linFragment;
    Unbinder unbinder1;

    public static ChaKancaigourfagment getInstance(String title) {
        ChaKancaigourfagment sf = new ChaKancaigourfagment();
        sf.mTitle = title;
        return sf;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    private ChushiZhangRightFragment mSortDetailFragment;

    private Context mContext;
    private LinearLayoutManager mLinearLayoutManager;


    String getData;
    String token;
    List<ShopListModel.DataBean> data = new ArrayList<>();

    ChuShiLeftAdapter chuShiLeftAdapter;


    FragmentTransaction fragmentTransaction;
    Bundle bundle;
    @BindView(R.id.layout_allloft)
    LinearLayout layout_all;
    @BindView(R.id.layout_nodata)
    LinearLayout layout_nodata;
    String startTime = "";
    String endTime = "";

    @BindView(R.id.layout_calenda_first)
    LinearLayout layout_calenda_first;
    @BindView(R.id.layout_calenda_second)
    LinearLayout layout_calenda_second;
    TimePickerView pvTime;
    @BindView(R.id.textview_calendafirst)
    TextView textview_calendafirst;
    @BindView(R.id.textview_calendasecond)
    TextView textview_calendasecond;

    @Override
    public View initView() {
        View v = LayoutInflater.from(getActivity()).inflate(R.layout.fr_chushicaigou, null);
        unbinder = ButterKnife.bind(this, v);
        EventBus.getDefault().register(this);
        TextView card_title_tv = (TextView) v.findViewById(R.id.card_title_tv);
        card_title_tv.setText(mTitle);
        mContext = getActivity();
        rvSort = (RecyclerView) v.findViewById(R.id.rv_sort);

        token = (String) SharePreferenceUtil.get(getActivity(), "token", "");
        getCaneda();
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String data = dateFormat.format(calendar.getTime());
        startTime = data;
        endTime = data;
//        textview_calendafirst.setText(startTime);
//        textview_calendasecond.setText(endTime);
        String replace_data = data.replace("-", ".");
        Log.d("replace_data", replace_data);
        textview_calendafirst.setText(replace_data);
        textview_calendasecond.setText(replace_data);
        //        Log.d("DingDanFragment3DingDanFragment3", getData);
        mLinearLayoutManager = new LinearLayoutManager(mContext);
        rvSort.setLayoutManager(mLinearLayoutManager);
        chuShiLeftAdapter = new ChuShiLeftAdapter(getActivity(), dataBeanList);

        rvSort.setAdapter(chuShiLeftAdapter);

        bundle = new Bundle();
        fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
        mSortDetailFragment = new ChushiZhangRightFragment();
        if (dataBeanList.size() == 0) {
            bundle.putString("right", MyStringUtils.beanToString("0"));
        } else {
            bundle.putString("right", MyStringUtils.beanToString(dataBeanList.get(0)));
        }

        fragmentTransaction.add(R.id.lin_fragment, mSortDetailFragment);
        fragmentTransaction.commit();
        mSortDetailFragment.setArguments(bundle);

        getData(token, "1", "", "", "0");
        initcrateData();

        return v;
    }

    String responseData;
    List<ChushiShenHeModel.DataBean> dataBeanList = new ArrayList<>();
    String sendData;

    @Override
    public void initData() {

    }

    public void getData(String token, String st, String startTime, String endTime, String flag) {
        HttpResponse.getApplyListByOrder(token, st, startTime, endTime, flag, new StringCallback(getActivity()) {

            @Override
            public void onSuccess(String s, Call call, Response response) {
                Log.d("getApplyListByOrder",s);

                if (dataBeanList.size() > 0) {
                    dataBeanList.clear();
                }

                BaseBean baseBean = new BaseBean();
                baseBean = GsonUtil.GsonToBean(s, BaseBean.class);
                if (baseBean.getCode() == 0) {
                    ChushiShenHeModel chushiShenHeModel = new ChushiShenHeModel();
                    chushiShenHeModel = GsonUtil.GsonToBean(s, ChushiShenHeModel.class);
                    dataBeanList.addAll(chushiShenHeModel.getData());
                    Log.d("Daddkdkdk", dataBeanList.size() + "");
                    sendData = s;
                    if (dataBeanList.size() == 0) {
                        layout_all.setVisibility(View.GONE);
                        layout_nodata.setVisibility(View.VISIBLE);
                    } else {
                        layout_all.setVisibility(View.VISIBLE);
                        layout_nodata.setVisibility(View.GONE);
                        chuShiLeftAdapter.setDataList(dataBeanList);
                        Intent intent = new Intent("canting.chushizhang.ChushiZhangRightFragment");

//                MyStringUtils.beanToString(dataBeanList.get(0))
                        intent.putExtra("pos", MyStringUtils.beanToString(dataBeanList.get(0)));
                        getActivity().sendBroadcast(intent);
                        chuShiLeftAdapter.setCheckedPosition(0);
                    }


                } else {
                    Toast.makeText(getActivity(), baseBean.getMessage() + "", Toast.LENGTH_SHORT).show();
                }

            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);
                layout_all.setVisibility(View.GONE);
                layout_nodata.setVisibility(View.VISIBLE);
            }
        });


        chuShiLeftAdapter.setOnItemClickListener(new ChuShiLeftAdapter.OnItemClickListener() {
            @Override
            public void onItemClickListener(View view, int pos, List<ChushiShenHeModel.DataBean> myLiveLists) {
                chuShiLeftAdapter.setCheckedPosition(pos);
                Intent intent = new Intent("canting.chushizhang.ChushiZhangRightFragment");

//                MyStringUtils.beanToString(dataBeanList.get(0))
                intent.putExtra("pos", MyStringUtils.beanToString(dataBeanList.get(pos)));
                getActivity().sendBroadcast(intent);
            }


        });

    }


    @Override
    public void onResume() {
        super.onResume();

    }


    private void setChecked(int position, boolean isLeft) {
        Log.d("p-------->", String.valueOf(position));
        chuShiLeftAdapter.setCheckedPosition(position);
    }


    @Override
    public void check(int position, boolean isScroll) {
        setChecked(position, isScroll);
    }

    public void onEventMainThread(EventBean eventBean) {

    }

    public void getCaneda() {
       /* Calendar selectedDate = Calendar.getInstance();//系统当前时间
        Calendar startDate = Calendar.getInstance();
        startDate.set(2020, 1, 1);
        Calendar endDate = Calendar.getInstance();
        int y = endDate.get(Calendar.YEAR);
        int m = endDate.get(Calendar.MONTH);
        int d = endDate.get(Calendar.DATE);
        endDate.set(y, m, d);*/
        Calendar selectedDate = Calendar.getInstance();//系统当前时间
        Calendar startDate = Calendar.getInstance();
        startDate.set(2018, 0, 1);
        Calendar endDate = Calendar.getInstance();
        int y = endDate.get(Calendar.YEAR);
        int m = endDate.get(Calendar.MONTH);
        int d = endDate.get(Calendar.DATE);
        endDate.set(2033, 12, 31);
        pvTime = new TimePickerBuilder(getActivity(), new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                switch (v.getId()) {
                    case R.id.layout_calenda_first:
                        textview_calendafirst.setText(getTime(date));
                        startTime = getTime(date);
                        Integer i = startTime.compareTo(endTime);
                        if (i > 0) {
                            Toast.makeText(getActivity(), "开始时间不能大于结束时间", Toast.LENGTH_SHORT).show();
                        } else {
                            getData(token, "1", startTime, endTime, "0");
                        }

                        break;
                    case R.id.layout_calenda_second:

                        endTime = getTime(date);
                        Integer i1 = startTime.compareTo(endTime);
                        if (i1 > 0) {
                            Toast.makeText(getActivity(), "开始时间不能大于结束时间", Toast.LENGTH_SHORT).show();
                        } else {
                            textview_calendasecond.setText(getTime(date));
                            getData(token, "1", startTime, endTime, "0");
                        }

                        break;
                }


            }
        }).setDate(selectedDate)
                .setRangDate(startDate, endDate)
                .setLayoutRes(R.layout.pickerview_custom_lunar, new CustomListener() {

                    @Override
                    public void customLayout(final View v) {
                        final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                        ImageView ivCancel = (ImageView) v.findViewById(R.id.iv_cancel);
                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvTime.returnData();
                                pvTime.dismiss();
                            }
                        });
                        ivCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvTime.dismiss();
                            }
                        });


                    }


                })
                .setType(new boolean[]{true, true, true, false, false, false})
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setDividerColor(getResources().getColor(R.color.canedacolor))

                .build();
    }

    private String getTime(Date date) {//可根据需要自行截取数据显示
        Log.d("getTime()", "choice date millis: " + date.getTime());
//        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }


    @OnClick({R.id.layout_calenda_first, R.id.layout_calenda_second, R.id.textview_calendafirst})
    public void onViewClicked(View view) {
        switch (view.getId()) {

            case R.id.layout_calenda_first:
            case R.id.textview_calendafirst:
                pvTime.show(layout_calenda_first);
                break;
            case R.id.layout_calenda_second:
            case R.id.textview_calendasecond:
                pvTime.show(layout_calenda_second);
                break;


        }
    }
    public void initcrateData() {
        HttpResponse.setHeartBeat(token, new StringCallback(getActivity()) {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                Log.d("initcrateData", s);
                Log.d("initcrateData", "执行心跳");
            }
        });
    }

}